<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests\MessageRequest;
use App\Http\Controllers\Controller;
use App\Model\Message;
use DB,Session;

class MessageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $request->flashOnly('title','type');

        $messages = Message::where('msg_status', 1)->where('msg_title', 'like', '%'.$request->get('title', '').'%');
        // 搜索条件
        if(9 != $request->get('type', 9)){
            $messages = $messages->where('msg_type', $request->get('type'));
        }
        
        $messages = $messages->orderBy('msg_time', 'desc')->paginate(15);
        
        return view('admin.message.index', compact('messages'));
    }

    /**
     * 发送系统消息
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.message.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(MessageRequest $request)
    {
        // 接收数据
        $data = $request->except('_token');
        $data['msg_time'] = date('Y-m-d H:i:s');
        $res = Message::insertGetId($data);
        if($res){
            $readData = [];
            // 获取所有用户id
            $ids = self::getUserId($data['msg_type'], $data['user_id']);
            foreach($ids as $id){
                $readData[$id]['user_id'] = $id;
                $readData[$id]['msg_id'] = $res;
            }
            DB::table('message_read')->insert($readData);
        }
        
        if($res){
            // 返回
            return redirect('/admin/message');
        } else {
            return back()->with('error', '消息发送失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $message = Message::where('id', $id)->first();
        if(!$message){
            return redirect('/admin/message');
        }
        return view('admin.message.show', compact('message'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->only('msg_status');
        $res = Message::where('id', $id)->update($data);
        if($res){
            return redirect('/admin/message');
        }
        return back()->with('error', '修改失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $r = ['status' => 0, 'info'=>''];
        
        $res = Message::where('id', $id)->update(['msg_status'=>0]);
        if ($res) {
           $r['status'] = 1;
           $r['info'] = '删除成功';
        } else {
            $r['info'] = '删除失败';
        }
        
        return response()->json($r);
    }
    
    // 获取所有的用户id
    protected static function getUserId($type = 0 , $user_id = 0)
    {
        if($user_id != 0 && $type == 1){
            return array($user_id);
        }
        switch ($type){
            case 0:
                $table = DB::table('user');
                $status = 'user_status';
            break;
            case 2:
                $table = DB::table('admin_user');
                $status = 'admin_status';
            break;
        }
        
        $ids = $table->where($status, '1')->lists('id');
        return $ids;
    }
    
    // 自动获取管理员消息
    public function getMessage()
    {
        // 获取当前用户id
        $user_id = Session::get('adminuserData')->id;
        $avartar = Session::get('adminuserData')->admin_avartar;
        
        // 获取所有的消息
        $messages = DB::table('message')->leftJoin('message_read', 'message.id','=','message_read.msg_id')
                ->where('message.msg_type', '2')
                ->where('message.msg_status', 1)
                ->where('message_read.user_id', $user_id)
                ->where('message_read.is_read', 0)
                ->orderBy('message.id', 'desc')
                ->get();
        if($messages){
            return response()->json(['status'=>1, 'info'=>$messages,'avartar'=>$avartar]);
        } else {
            return response()->json(['status'=>0, 'info'=>$messages,'avartar'=>$avartar]);
        }
    }
}
